package cn.vihub.service.impl;

import cn.vihub.param.ShopGoodsSpecParam;
import cn.vihub.pojo.ShopGoodsCategory;
import cn.vihub.service.ShopGoodsCategoryService;
import cn.vihub.vo.ShopGoodsSpecVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.vihub.mapper.ShopGoodsSpecMapper;
import cn.vihub.pojo.ShopGoodsSpec;
import cn.vihub.service.ShopGoodsSpecService;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Author: 秋晚
 * @Date:  2025/7/28 19:30
 * @Description: 
 **/

@Service
@Transactional(rollbackFor = Exception.class)
public class ShopGoodsSpecServiceImpl extends ServiceImpl<ShopGoodsSpecMapper, ShopGoodsSpec> implements ShopGoodsSpecService{

    @Autowired
    ShopGoodsSpecMapper shopGoodsSpecMapper;

    @Autowired
    ShopGoodsCategoryService shopGoodsCategoryService;
    @Override
    public IPage<ShopGoodsSpecVo> getShopGoodsSpec(ShopGoodsSpecParam shopGoodsSpecParam) {
        //创建分页对象
        IPage<ShopGoodsSpecVo> iPage = new Page<>();
        //查询所有数据
        LambdaQueryWrapper<ShopGoodsSpecVo> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        IPage<ShopGoodsSpecVo> shopGoodsSpecVoIPage=shopGoodsSpecMapper.selectByPage(iPage,lambdaQueryWrapper);

        //获取所有分类
        List<ShopGoodsCategory> shopGoodsCategoryList = shopGoodsCategoryService.list();
        //把查询到的分类列表转化为HashMap集合
        Map<Integer, String> shopCategoryMap =
                shopGoodsCategoryList.stream()
                        .collect(Collectors.toMap(ShopGoodsCategory::getId, ShopGoodsCategory::getName));


        //根据查询到的数据进行查询拼接分类名称返回
        for (ShopGoodsSpecVo record : shopGoodsSpecVoIPage.getRecords()) {
            //获取每一个record对象
            String goodsCategoryPath = record.getGoodsCategoryPath();
            //将字符串转化为数组'
            String[] split = goodsCategoryPath.split(",");
            //创建拼接字符串的集合
            ArrayList<String> str = new ArrayList<>();
            for (String categoryId : split) {
                String s = shopCategoryMap.get(Integer.parseInt(categoryId));
                if(s==null){
                    continue;
                }
                str.add(s);
            }
            String categoryName = String.join("/", str);
            record.setGoodsCategoryName(categoryName);
        }
        return shopGoodsSpecVoIPage;
    }
}
